package xyz.liut.autolaunch;

import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.util.Calendar;

import xyz.liut.logcat.L;

/**
 * Create by liut on 20-10-27
 */
public class ExecJob extends JobService {

    private static final String TAG = "ExecJob";

    public static void setup(Context context) {
        JobScheduler scheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
        if (scheduler == null) {
            return;
        }
        scheduler.cancelAll();

        L.d("", "");

        // 单个计时
        seven(context, scheduler);

        // 循环计时
        SpTool spTool = SpTool.getDefault(context);
        boolean swTiming = Boolean.parseBoolean(spTool.get(Constants.Default.KEY_SW_TIMING, "false"));
        if (swTiming) {
            time2(context, scheduler);
        }
    }

    private static void time2(Context context, JobScheduler scheduler) {
        ComponentName componentName = new ComponentName(context.getApplicationContext(), ExecJob.class.getName());
        JobInfo.Builder builder = new JobInfo.Builder(1123, componentName)
                .setPersisted(true);

        SpTool spTool = SpTool.getDefault(context);
        int timing;
        try {
            timing = Integer.parseInt(spTool.get(Constants.Default.KEY_TIMING, "0"));
        } catch (Exception e) {
            return;
        }
        builder.setMinimumLatency(1000L * 60 * timing).setOverrideDeadline(1000L * 60 * (timing + 5));
//            builder.setPeriodic(60 * 1000L * timing);

        JobInfo jobInfo = builder.build();
        int scheduleResult = scheduler.schedule(jobInfo);

        L.d("循环 " + jobInfo.getMinLatencyMillis() / 60 / 1000L + " 分钟: " + (scheduleResult == JobScheduler.RESULT_SUCCESS));
    }

    /**
     * 早7点
     */
    private static void seven(Context context, JobScheduler scheduler) {
        SpTool tool = SpTool.getDefault(context);
        String timeList = tool.get(Constants.Default.KEY_TIMES);
        String[] timeArray = timeList.split("#");
        for (int a = 0; a < timeArray.length; a++) {
            String time = timeArray[a];
            if (TextUtils.isEmpty(time)) continue;

            String[] ss = time.split(": ");
            int hour = Integer.parseInt(ss[0]);
            int min = Integer.parseInt(ss[1]);
            ComponentName componentName = new ComponentName(context.getApplicationContext(), ExecJob.class.getName());
            JobInfo.Builder builder = new JobInfo.Builder(a, componentName)
                    .setPersisted(true);

            Calendar now = Calendar.getInstance();
            Log.d(TAG, "time " + now.getTime());
            Calendar targetTime = (Calendar) now.clone();
            targetTime.set(Calendar.HOUR_OF_DAY, hour);
            targetTime.set(Calendar.MINUTE, min);
            targetTime.set(Calendar.SECOND, 0);
            targetTime.set(Calendar.MILLISECOND, 0);
            if (targetTime.before(now)) {
                targetTime.add(Calendar.DATE, 1);
            }
            long latencyTime = targetTime.getTimeInMillis() - now.getTimeInMillis();
            builder.setMinimumLatency(latencyTime).setOverrideDeadline(latencyTime + 1000L * 60);

            JobInfo jobInfo = builder.build();
            int scheduleResult = scheduler.schedule(jobInfo);

            L.d("定时 " + time + ": " + (scheduleResult == JobScheduler.RESULT_SUCCESS));

        }
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        execLaunch();
        setup(this);
        return false;
    }


    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    private void execLaunch() {
        SpTool spTool = SpTool.getDefault(this);

        String pkg = spTool.get(Constants.Default.KEY_PKG);
        boolean isRoot = Boolean.parseBoolean(spTool.get(Constants.Default.KEY_ROOT, "false"));

        LaunchTool.launch(this, pkg, isRoot);

    }

}
